import { CommandHandler, ICommandHandler, EventBus } from '@nestjs/cqrs'
import { ValidateUserLocalCommand } from './validate-user-local.command'
import { UserEntity } from '@/user/entities/user.mysql.entity'
import { Repository } from 'typeorm'
import { BadRequestException, Inject } from '@nestjs/common'
import { BcryptService } from '@/shared/common/bcryptjs.service'

@CommandHandler(ValidateUserLocalCommand)
export class ValidateUserLocalCommandHandler implements ICommandHandler<ValidateUserLocalCommand>{
  constructor(
    private readonly eventBus: EventBus,
    @Inject('USER_REPOSITORY')
    private readonly userRepository: Repository<UserEntity>,
  ) { }
  async execute(event: ValidateUserLocalCommand) {
    const { username, password } = event.params
    const user = await this.userRepository.findOne({ where: { username } })
    if (!user) {
      throw new BadRequestException("用户不存在")
    }
    const isPasswordMatches = await BcryptService.compare(password, user.password)
    if (!isPasswordMatches) {
      throw new BadRequestException("密码错误")
    }
    return user
  }
}